<template>
  <div class="edit-container">
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      v-show="!showCropper"
    />
    <div class="infophoto">
      <!-- 上传组件 -->
      <van-uploader :after-read="afterRead" />
      <div class="avator">
        <van-image
          width="120"
          height="120"
          round
          fit="cover"
          :src="userInfo.photo"
        />
      </div>
    </div>
    <van-cell-group>
      <van-cell
        title="昵称"
        :value="userInfo.name"
        is-link
        @click="showNameEdit"
      />
      <van-cell
        title="性别"
        :value="userInfo.gender === 1 ? '女' : '男'"
        is-link
        @click="showGenderEdit"
      />
      <van-cell
        title="生日"
        :value="userInfo.birthday"
        is-link
        @click="showTime"
      />
    </van-cell-group>
    <!-- 弹出框--修改昵称 -->
    <van-dialog
      v-model="showName"
      @confirm="updateNickname"
      title="修改昵称"
      show-cancel-button
    >
      <van-cell-group>
        <van-field
          v-model="nickName"
          placeholder="请修改昵称"
          ref="nameField"
        />
      </van-cell-group>
    </van-dialog>
    <!-- 性别弹出层 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="onClickLeft"
      />
      <van-cell-group>
        <van-cell title="男" is-link @click="editGender(0)" />
        <van-cell title="女" is-link @click="editGender(1)" />
      </van-cell-group>
    </van-popup>
    <!-- 时间选择 -->
    <van-popup v-model="timeShow" position="bottom"
      ><van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="editBirthday"
        @cancel="cancelBirthday"
    /></van-popup>
    <!-- 裁剪框 -->
    <div class="cropper-box" v-show="showCropper">
      <vueCropper
        ref="cropper"
        :img="img"
        autoCrop
        autoCropWidth="120"
        autoCropHeight="120"
        fixed
      ></vueCropper>
      <!-- 按钮 -->
      <van-button type="primary" class="cancel" @click="showCropper = false"
        >取消</van-button
      ><van-button type="primary" class="confirm" @click="cropperConfirm"
        >确认</van-button
      >
    </div>
  </div>
</template>

<script>
import { editUserAvator, editUserInfo } from '../../api/edit'
import { mapMutations, mapState } from 'vuex'
import moment from 'moment'
// 导入裁剪组件
import { VueCropper } from 'vue-cropper'
export default {
  // 注册裁剪组件
  components: { VueCropper },
  computed: {
    // 将用户信息隐射过来
    ...mapState(['userInfo'])
  },
  name: 'edit',
  created () {},
  data () {
    return {
      showName: false,
      nickName: '',
      showPopup: false,
      minDate: new Date(1990, 0, 1),
      maxDate: new Date(2030, 0, 1),
      // 这里组件显示不了，需要修改时间格式
      currentDate: new Date(),
      timeShow: false,
      img: '',
      showCropper: false
    }
  },
  methods: {
    // 上传组件
    afterRead (file) {
      // 显示裁剪框
      this.showCropper = true
      // 设置需要裁剪的图片
      this.img = file.content
    },
    // 裁剪确认
    cropperConfirm () {
      // 获取截图的blob数据
      this.$refs.cropper.getCropBlob(data => {
        // do something
        console.log(data)
        const fd = new FormData()
        fd.append('photo', data)
        // console.log(fd.get('photo'))
        editUserAvator(fd).then(res => {
          // console.log(res)
          // 弹窗提示
          this.$toast.success('更新成功')
          // 更新vuex
          this.setUserInfo({
            ...this.userInfo,
            photo: res.data.data.photo
          })
          // 隐藏裁剪框
          this.showCropper = false
        })
      })
    },
    // 显示时间框
    showTime () {
      this.timeShow = true
      // 将时间格式再次改回 DatetimePicker 可识别的格式
      this.currentDate = new Date(this.userInfo.birthday)
    },
    // 编辑生日
    // 取消
    cancelBirthday () {
      this.timeShow = false
    },
    // 确认
    editBirthday () {
      // 时间格式不对，需要格式化，再发起请求
      const birthday = moment(this.currentDate).format('YYYY-MM-DD')
      console.log(birthday)
      // 发起请求，修改vuex里的数据
      editUserInfo({ birthday }).then(res => {
        console.log(res)
        // 弹出更新成功提示 更新vuex数据
        this.$toast.success('修改成功')
        this.setUserInfo({
          ...this.userInfo,
          birthday
        })
      })
      this.timeShow = false
    },
    onClickLeft () {
      this.showPopup = false
    },
    ...mapMutations(['setUserInfo']),
    showNameEdit () {
      // 显示弹出框
      this.showName = true
      // 渲染数据
      this.nickName = this.userInfo.name
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs.nameField.focus()
      })
    },
    // ---------------------------

    // 修改昵称
    updateNickname () {
      editUserInfo({ name: this.nickName }).then(res => {
        // 1.弹窗提示
        this.$toast.success('更新成功')
        // 2.更新vuex数据
        this.setUserInfo({
          ...this.userInfo,
          name: res.data.data.name
        })
      })
    },
    // 修改性别
    showGenderEdit () {
      this.showPopup = true
    },
    editGender (gender) {
      editUserInfo({ gender }).then(res => {
        // console.log(res)
        // 弹窗提示
        this.$toast.success('更新成功')
        // 更新vuex数据
        this.setUserInfo({
          ...this.userInfo,
          // 传的值等于undefined 就改成0
          gender: res.data.data.gender === 1 ? 1 : 0
        })
        // 隐藏弹出层
        this.showPopup = false
      })
    }
  }
}
</script>

<style lang="less">
.edit-container {
  .infophoto {
    position: relative;
    .van-uploader {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      opacity: 0;
      z-index: 999;
    }
    .avator {
      display: flex;
      justify-content: center;
      padding: 20px;
    }
  }
  .van-dialog__content {
    padding: 10px;
    .van-cell-group {
      border: 1px solid #dadada;
    }
  }

  .cropper-box {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    .cancel {
      position: absolute;
      left: 0;
      bottom: 0;
    }
    .confirm {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>
